package com.gxc.webcore.controller;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.gxc.webcore.util.ContextUtil;
import com.gxc.webcore.util.RequestUtil;

/**
 * 所有do请求的统一入口
 * 
 * @author gxc
 * 
 */
public class BaseController extends AbstractController {

	private Logger logger = Logger.getLogger(this.getClass());

	@SuppressWarnings({ "rawtypes" })
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// TODO 请求url
		String url = RequestUtil.getUrl(request);
		if (url.lastIndexOf("/") < 0) {
			logger.warn("该链接不存在或已删除,本次url:" + url);
			return ViewController.info(request, response, "该链接不存在或已删除！", null);
		}

		// TODO 获取controller名称和method名称
		String beanName = url.substring(0, url.lastIndexOf("/")) + "Controller";
		String methodName = url.substring(url.lastIndexOf("/") + 1,
				url.length() - 3);

		// TODO 获取controller
		Object objInstance = ContextUtil.getBean(beanName);
		if (objInstance == null) {
			// 请求的controller不存在
			logger.warn("请求的controller不存在,本次url:" + url);
			return ViewController.info(request, response, "该链接不存在或已删除！", null);
		}

		// TODO 获取method
		Class parameterTypes[] = { HttpServletRequest.class,
				HttpServletResponse.class };
		Object args[] = { request, response };
		Method method = null;
		try {
			method = objInstance.getClass().getMethod(methodName,
					parameterTypes);
		} catch (Exception e) {
			// 请求的方法不存在
			logger.warn("请求的方法不存在,本次url:" + url);
			return ViewController.info(request, response, "该链接不存在或已删除！", null);
		}

		// TODO 执行
		ModelAndView modelAndView = null;
		try {
			modelAndView = (ModelAndView) method.invoke(objInstance, args);
		} catch (Exception e) {
			// 执行出错
			logger.warn("系统内部错误,本次url:" + url);
			e.printStackTrace();
			return ViewController.error(request, response, null);
		}

		return modelAndView;
	}

}
